﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using STS.Schema.Collections;
using System.Configuration;
using System.Data.Common;
using STS.Schema.Base;
using STS.Common;
using STS.Interfaces;

namespace STS.Schema
{
    public static class DbContext
    {
        private static Lazy<Dictionary<string, DbServer>> _servers = new Lazy<Dictionary<string, DbServer>>(() => GetServers());
        public static List<DbServer> Servers
        {
            get
            {
                return new List<DbServer>(_servers.Value.Select(item => item.Value));
            }
        }

        private static Dictionary<string, DbServer> GetServers()
        {
            Dictionary<string, DbServer> servers = new Dictionary<string, DbServer>();
            foreach (ConnectionStringSettings css in ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).ConnectionStrings.ConnectionStrings)
            {
                ConnectionInfo cInfo = new ConnectionInfo(css.ConnectionString, css.ProviderName);
                servers.Add(css.Name, DbUtils.GetServer(cInfo));
            }
            return servers;
        }

        public static void Refresh()
        {
            _servers = new Lazy<Dictionary<string, DbServer>>(() => GetServers());
        }
    }
}
